package personal.learn.algorithm;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * AES算法
 *
 * @author Chai yansheng
 * @create 2019/8/28
 **/
public class AESAlgorithm {
    public static void main(String[] args) {
        String password = "123456", content = "我是小灰";
        try {
            // 创建AES的Key的生产者
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            // 利用用户密码作为随机数初始化
            keyGenerator.init(128, new SecureRandom(password.getBytes()));
            // 根据用户密码生成一个秘钥
            SecretKey secretKey = keyGenerator.generateKey();
            // 返回基本编码格式的秘钥
            byte[] encodeFormat = secretKey.getEncoded();
            // 转换为AES专用秘钥
            SecretKeySpec key = new SecretKeySpec(encodeFormat, "AES");
            // 创建加密器
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            byte[] byteContent = content.getBytes("utf-8");
            // 初始化为加密模式的密码器
            cipher.init(Cipher.ENCRYPT_MODE, key);
            // 加密
            byte[] result = cipher.doFinal(byteContent);
            System.out.println(result);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }

    }
}
